extends CanvasLayer

@onready var health_bar = $HUD/HealthBar
@onready var experience_bar = $HUD/ExperienceBar
@onready var level_label = $HUD/LevelLabel
@onready var time_label = $HUD/TimeLabel
@onready var level_up_screen = $LevelUpScreen
@onready var upgrade_option_1 = $LevelUpScreen/VBoxContainer/UpgradeOption1
@onready var upgrade_option_2 = $LevelUpScreen/VBoxContainer/UpgradeOption2
@onready var upgrade_option_3 = $LevelUpScreen/VBoxContainer/UpgradeOption3

var game_time = 0.0
var player_node = null

# Pool of possible upgrades (IDs should match Player.gd apply_upgrade)
var upgrade_pool = [
	{"id": "add_knife", "text": "获得新飞刀"},
	{"id": "upgrade_knife_damage", "text": "飞刀伤害 +5"},
	{"id": "upgrade_knife_speed", "text": "飞刀频率 +10%"}, # Example text
	{"id": "increase_health", "text": "最大生命 +20"},
	# Add more upgrades here for different weapons, stats etc.
	{"id": "increase_speed", "text": "移动速度 +10%"}, # Need to implement this in Player.gd
	{"id": "increase_pickup", "text": "拾取范围 +15%"}  # Need to implement this in Player.gd (scale PickupArea)
]
var current_upgrade_choices = []


func _ready():
	level_up_screen.hide() # Start with level up screen hidden
	# Find the player node (adjust path if needed)
	player_node = get_tree().get_first_node_in_group("player")
	if player_node:
		# Connect signals from Player to UI update functions
		player_node.connect("health_changed", _on_player_health_changed)
		player_node.connect("experience_changed", _on_player_experience_changed)
		player_node.connect("leveled_up", _on_player_leveled_up)
		# Initial UI setup
		_on_player_health_changed(player_node.current_health, player_node.max_health)
		_on_player_experience_changed(player_node.experience, player_node.experience_needed, player_node.level)
	else:
		print("ERROR: UI couldn't find player node!")

	# Connect button presses for upgrades
	upgrade_option_1.connect("pressed", _on_upgrade_selected.bind(0))
	upgrade_option_2.connect("pressed", _on_upgrade_selected.bind(1))
	upgrade_option_3.connect("pressed", _on_upgrade_selected.bind(2))


func _process(delta):
	if not get_tree().paused: # Only update time if game is not paused
		game_time += delta
		# Format time MM:SS
		var minutes = int(game_time / 60)
		var seconds = int(game_time) % 60
		time_label.text = "Time: %02d:%02d" % [minutes, seconds]


func _on_player_health_changed(new_health, max_health):
	health_bar.max_value = max_health
	health_bar.value = new_health


func _on_player_experience_changed(new_xp, needed_xp, current_level):
	experience_bar.max_value = needed_xp
	experience_bar.value = new_xp
	level_label.text = "Level: " + str(current_level)


func _on_player_leveled_up(current_level):
	# Generate 3 unique upgrade options
	current_upgrade_choices.clear()
	var available_upgrades = upgrade_pool.duplicate() # Make a copy to modify
	available_upgrades.shuffle() # Randomize

	for i in range(min(3, available_upgrades.size())): # Take up to 3 options
		current_upgrade_choices.append(available_upgrades[i])

	# Update button text (assuming 3 buttons exist)
	if current_upgrade_choices.size() > 0:
		upgrade_option_1.text = current_upgrade_choices[0]["text"]
		upgrade_option_1.show()
	else:
		upgrade_option_1.hide()

	if current_upgrade_choices.size() > 1:
		upgrade_option_2.text = current_upgrade_choices[1]["text"]
		upgrade_option_2.show()
	else:
		upgrade_option_2.hide()

	if current_upgrade_choices.size() > 2:
		upgrade_option_3.text = current_upgrade_choices[2]["text"]
		upgrade_option_3.show()
	else:
		upgrade_option_3.hide()

	# Show the level up screen
	level_up_screen.show()


func _on_upgrade_selected(choice_index):
	if choice_index < current_upgrade_choices.size():
		var selected_upgrade = current_upgrade_choices[choice_index]
		print("UI: Upgrade selected - ", selected_upgrade["text"])
		# Tell the player to apply the chosen upgrade
		if player_node:
			player_node.apply_upgrade(selected_upgrade["id"])

		# Hide the level up screen
		level_up_screen.hide()
		# Game is unpaused within Player.gd's apply_upgrade function
	else:
		print("ERROR: Invalid upgrade choice index")
		# Failsafe: hide screen and unpause if something went wrong
		level_up_screen.hide()
		if player_node: get_tree().paused = false
